<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/static/lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="/static/css/public.css" media="all">
    <style>
        .layui-form-pane .layui-form-label {
            width: 120px;
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 3px 3px 3px 3px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">订单号</label>
                            <div class="layui-input-inline">
                                <input type="text" name="orderNo" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">供应商名称</label>
                            <div class="layui-input-inline">
                                <input type="text" name="supName" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">签约日期</label>
                            <div class="layui-input-inline">
                                <input type="text" name="signDate" id="signDate" autocomplete="off" class="layui-input" placeholder="yyyy-MM-dd">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">状态</label>
                            <div class="layui-input-inline">
                                <select name="docStatus">
                                    <option value="">请选择</option>
                                    <option value="10">准备</option>
                                    <option value="11">驳回</option>
                                    <option value="15">修改</option>
                                    <option value="30">待审</option>
                                    <option value="70">执行</option>
                                    <option value="80">完结</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit
                                    lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索
                            </button>
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit
                                    lay-filter="data-refresh-btn"><i class="layui-icon layui-icon-refresh"></i> 刷新
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
<!--                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加</button>-->
                <button id="sumButton" style="float: right; font-size: 16px"
                        class="layui-btn layui-btn-primary layui-btn-sm"><i
                        class="fa fa-arrows-h">采购订单总金额：</i><span id="sumPrice"></span></li></button>
            </div>
        </script>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>
        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="show">查看</a>
            {{# if(d.docStatus == 30 && d.userRoleType != undefined && (d.userRoleType == 0 || d.userRoleType == 1)) { }}
            <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="approve">通过</a>
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="reject">驳回</a>
            {{# } }}
        </script>

        <!-- 执行中的订单分页查询 -->
        <div style="margin-top: 30px;">
            <fieldset class="table-search-fieldset">
                <legend>执行中的订单</legend>
                <div style="margin: 3px 3px 3px 3px">
                    <form class="layui-form layui-form-pane" action="">
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">订单号</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="execOrderNo" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label">供应商名称</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="execSupName" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label">签约日期</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="execSignDate" id="execSignDate" autocomplete="off" class="layui-input" placeholder="yyyy-MM-dd">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <button type="submit" class="layui-btn layui-btn-primary" lay-submit
                                        lay-filter="exec-search-btn"><i class="layui-icon">&#xe615;</i> 搜 索
                                </button>
                                <button type="submit" class="layui-btn layui-btn-primary" lay-submit
                                        lay-filter="exec-refresh-btn"><i class="layui-icon layui-icon-refresh"></i> 刷新
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </fieldset>

            <script type="text/html" id="execToolbarDemo">
                <div class="layui-btn-container">
                    <button id="execSumButton" style="float: right; font-size: 16px"
                            class="layui-btn layui-btn-primary layui-btn-sm"><i
                            class="fa fa-arrows-h">执行中订单总金额：</i><span id="execSumPrice"></span></button>
                </div>
            </script>

            <table class="layui-hide" id="execTableId" lay-filter="execTableFilter"></table>
            <script type="text/html" id="execTableBar">
                <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="show">查看</a>
                {{# if(d.docStatus == 70 && d.userRoleType != undefined && (d.userRoleType == 0 || d.userRoleType == 1)) { }}
                <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="generateContract">生成合同</a>
                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="rejectForRevision">打回重审</a>
                {{# } }}
            </script>
        </div>

    </div>
</div>
<script src="/static/lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
<script src="/static/lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="/static/lib/jq-module/jquery.particleground.min.js" charset="utf-8"></script>
<script src="/static/js/common.js"></script>
<script>
    var lay, form, table;
    layui.use(['form', 'table', 'laydate'], function () {
        lay = layui.jquery;
        form = layui.form;
        util = layui.util;
        table = layui.table;
        laydate = layui.laydate;
        
        // 获取用户角色信息
        let user = $.common.getUserInfo();
        let userRoleType = user ? user.roleType : -1;
        
        // 初始化日期选择器
        laydate.render({
            elem: '#signDate',
            type: 'date',
            format: 'yyyy-MM-dd'
        });
        
        // 初始化执行中订单的日期选择器
        laydate.render({
            elem: '#execSignDate',
            type: 'date',
            format: 'yyyy-MM-dd'
        });
        
        table.render({
            elem: '#currentTableId',
            url: '/purchaseOrder/pages',
            toolbar: '#toolbarDemo',
            method: "post",
            request: {
                pageName: "pageNum",
                limitName: "pageSize"
            },
            contentType: "application/json; charset=utf-8",
            where: {
                param: {
                    docStatus: '30',  // 只显示待审状态的订单
                    redFlag: 'NO'     // 只显示非历史订单
                }
            },
            parseData: function(res) {
                // 为每行数据添加用户角色信息
                console.log('用户角色类型:', userRoleType);
                if (res.data && res.data.length > 0) {
                    res.data.forEach(function(item) {
                        item.userRoleType = userRoleType;
                    });
                }
                return res;
            },
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [[
                {type: "checkbox", width: 50},
                {field: 'purchaseOrderId', width: 65, title: 'ID', sort: true},
                {field: 'orderNo', width: 150, title: '采购订单号'},
                {field: 'supName', width: 120, title: '供应商名称'},
                {
                    field: 'signDate',
                    width: 100,
                    title: '签约日期',
                    templet: "<div>{{layui.util.toDateString(d.signDate, 'yyyy-MM-dd')}}</div>"
                },
                {
                    field: 'validStartDate',
                    width: 100,
                    title: '有效起始日期',
                    templet: "<div>{{layui.util.toDateString(d.validStartDate, 'yyyy-MM-dd')}}</div>"
                },
                {
                    field: 'validEndDate',
                    width: 100,
                    title: '有效结束日期',
                    templet: "<div>{{layui.util.toDateString(d.validEndDate, 'yyyy-MM-dd')}}</div>"
                },
                {field: 'totalAmount', width: 140, title: '订单总金额'},
                {field: 'totalTaxFreeAmount', width: 140, title: '不含税总金额'},
                {field: 'taxRate', width: 100, title: '税率'},
                {field: 'taxAmount', width: 140, title: '增值税金额'},
                {field: 'docStatus', width: 100, title: '状态', templet: function(d){
                    var statusMap = {
                        '10': '准备',
                        '11': '驳回',
                        '15': '修改',
                        '30': '待审',
                        '70': '执行',
                        '80': '完结'
                    };
                    return statusMap[d.docStatus] || '';
                }},
                {
                    field: 'createTime',
                    width: 120,
                    title: '创建时间',
                    templet: "<div>{{layui.util.toDateString(d.createTime, 'yyyy-MM-dd')}}</div>"
                },
                {field: 'creatorId', width: 100, title: '创建人'},
                {
                    field: 'updateTime',
                    width: 120,
                    title: '修改时间',
                    templet: "<div>{{layui.util.toDateString(d.updateTime, 'yyyy-MM-dd')}}</div>"
                },
                {title: '操作', minWidth: 170, toolbar: '#currentTableBar', align: "center", fixed: 'right'}
            ]],
            done: function (res, curr, count) {  //隐藏列

            },
            limits: [5, 10, 15, 20, 25, 50, 100, 500],
            limit: 10,
            page: true
        });

        // 初始化执行中的订单表格
        table.render({
            elem: '#execTableId',
            url: '/purchaseOrder/pages',
            toolbar: '#execToolbarDemo',
            method: "post",
            request: {
                pageName: "pageNum",
                limitName: "pageSize"
            },
            contentType: "application/json; charset=utf-8",
            where: {
                param: {
                    docStatus: '70',  // 只显示执行状态的订单
                    redFlag: 'NO'     // 只显示非历史订单
                }
            },
            parseData: function(res) {
                // 为每行数据添加用户角色信息
                console.log('执行中订单用户角色类型:', userRoleType);
                if (res.data && res.data.length > 0) {
                    res.data.forEach(function(item) {
                        item.userRoleType = userRoleType;
                    });
                }
                return res;
            },
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [[
                {type: "checkbox", width: 50},
                {field: 'purchaseOrderId', width: 65, title: 'ID', sort: true},
                {field: 'orderNo', width: 150, title: '采购订单号'},
                {field: 'supName', width: 120, title: '供应商名称'},
                {
                    field: 'signDate',
                    width: 100,
                    title: '签约日期',
                    templet: "<div>{{layui.util.toDateString(d.signDate, 'yyyy-MM-dd')}}</div>"
                },
                {
                    field: 'validStartDate',
                    width: 100,
                    title: '有效起始日期',
                    templet: "<div>{{layui.util.toDateString(d.validStartDate, 'yyyy-MM-dd')}}</div>"
                },
                {
                    field: 'validEndDate',
                    width: 100,
                    title: '有效结束日期',
                    templet: "<div>{{layui.util.toDateString(d.validEndDate, 'yyyy-MM-dd')}}</div>"
                },
                {field: 'totalAmount', width: 140, title: '订单总金额'},
                {field: 'totalTaxFreeAmount', width: 140, title: '不含税总金额'},
                {field: 'taxRate', width: 100, title: '税率'},
                {field: 'taxAmount', width: 140, title: '增值税金额'},
                {field: 'docStatus', width: 100, title: '状态', templet: function(d){
                    var statusMap = {
                        '10': '准备',
                        '11': '驳回',
                        '15': '修改',
                        '30': '待审',
                        '70': '执行',
                        '80': '完结'
                    };
                    return statusMap[d.docStatus] || '';
                }},
                {
                    field: 'createTime',
                    width: 120,
                    title: '创建时间',
                    templet: "<div>{{layui.util.toDateString(d.createTime, 'yyyy-MM-dd')}}</div>"
                },
                {field: 'creatorId', width: 100, title: '创建人'},
                {
                    field: 'updateTime',
                    width: 120,
                    title: '修改时间',
                    templet: "<div>{{layui.util.toDateString(d.updateTime, 'yyyy-MM-dd')}}</div>"
                },
                {title: '操作', minWidth: 250, toolbar: '#execTableBar', align: "center", fixed: 'right'}
            ]],
            done: function (res, curr, count) {
                // 计算执行中订单总金额
                var totalAmount = 0;
                if (res.data && res.data.length > 0) {
                    res.data.forEach(function(item) {
                        if (item.totalAmount) {
                            totalAmount += parseFloat(item.totalAmount);
                        }
                    });
                }
                $('#execSumPrice').text(totalAmount.toFixed(2));
            },
            limits: [5, 10, 15, 20, 25, 50, 100, 500],
            limit: 10,
            page: true
        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            //执行搜索重载
            search(data);
            return false;
        });

        form.on('submit(data-refresh-btn)', function (data) {
            // 提交刷新了当前页面
        });

        // 监听执行中订单搜索操作
        form.on('submit(exec-search-btn)', function (data) {
            //执行搜索重载
            execSearch(data);
            return false;
        });

        form.on('submit(exec-refresh-btn)', function (data) {
            // 刷新执行中订单表格
            table.reload('execTableId');
        });

        /**
         * toolbar监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                var index = layer.open({
                    title: '添加采购订单',
                    type: 2,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['95%', '95%'],
                    content: '/static/page1/order1/page2/add.html',
                });
                lay(window).on("resize", function () {
                    layer.full(index);
                });
            }
        });

        //监听表格复选框选择
        table.on('checkbox(currentTableFilter)', function (obj) {
            console.log(obj)
        });

        //监听执行中订单表格复选框选择
        table.on('checkbox(execTableFilter)', function (obj) {
            console.log(obj)
        });

        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                var index = layer.open({
                    title: '修改采购订单',
                    type: 2,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['95%', '95%'],
                    content: '/static/page1/order1/page2/add.html?purchaseOrderId=' + data.purchaseOrderId
                        + "&supId=" + data.supId,
                    data: data,
                    success: function (index, layero) {
                        var body = layer.getChildFrame('body', layero);
                        for (let key in data) {
                            if ('signDate' == key) {
                                let a = util.toDateString(data[key], 'yyyy-MM-dd')
                                body.find("#" + key).val(a);
                                continue;
                            }
                            if ('validStartDate' == key) {
                                let a = util.toDateString(data[key], 'yyyy-MM-dd')
                                body.find("#" + key).val(a);
                                continue;
                            }
                            if ('validEndDate' == key) {
                                let a = util.toDateString(data[key], 'yyyy-MM-dd')
                                body.find("#" + key).val(a);
                                continue;
                            }
                            body.find("#" + key).val(data[key]);
                        }
                    },
                    end: function () {

                    }
                });
                lay(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            }  else if(obj.event === 'show') {
                var index = layer.open({
                    title: '查看采购订单',
                    type: 2,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['95%', '95%'],
                    content: '/static/page1/order1/page2/add.html?purchaseOrderId=' + data.purchaseOrderId
                        + "&supId=" + data.supId+"&isShow=true",
                    data: data,
                    success: function (index, layero) {
                        var body = layer.getChildFrame('body', layero);
                        for (let key in data) {
                            if ('signDate' == key) {
                                let a = util.toDateString(data[key], 'yyyy-MM-dd')
                                body.find("#" + key).val(a);
                                continue;
                            }
                            if ('validStartDate' == key) {
                                let a = util.toDateString(data[key], 'yyyy-MM-dd')
                                body.find("#" + key).val(a);
                                continue;
                            }
                            if ('validEndDate' == key) {
                                let a = util.toDateString(data[key], 'yyyy-MM-dd')
                                body.find("#" + key).val(a);
                                continue;
                            }
                            body.find("#" + key).val(data[key]);
                        }
                    },
                    end: function () {

                    }
                });
                lay(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            } else if (obj.event === 'approve') {
                // 审核通过
                layer.confirm('确定通过此订单？', function (index) {
                    $.xAjax('/purchaseOrder/approve/' + data.purchaseOrderId, 'POST', JSON.stringify({}), {
                        onSuccess: function (result) {
                            if (result.code == 0) {
                                $.common.showSuccessMessage('订单审核通过');
                                table.reload('currentTableId');
                            } else {
                                $.common.showErrorMessage(result.message);
                            }
                        }
                    });
                    layer.close(index);
                });
            } else if (obj.event === 'reject') {
                // 审核驳回
                layer.prompt({
                    title: '驳回原因',
                    formType: 2,
                    area: ['400px', '200px']
                }, function(value, index, elem) {
                    if (!value || value.trim() == '') {
                        $.common.showErrorMessage('请填写驳回原因');
                        return;
                    }
                    
                    $.xAjax('/purchaseOrder/reject/' + data.purchaseOrderId, 'POST', JSON.stringify({rejectReason: value}), {
                        onSuccess: function (result) {
                            if (result.code == 0) {
                                $.common.showSuccessMessage('订单已驳回');
                                table.reload('currentTableId');
                            } else {
                                $.common.showErrorMessage(result.message);
                            }
                        }
                    });
                    layer.close(index);
                });
            } else if (obj.event === 'delete') {
                layer.confirm('确定删除？', function (index) {
                    let url = "/purchaseOrder/delete/" + obj.data.purchaseOrderId;
                    let callback = {
                        onSuccess: function (result) {
                            if (result.code == 0) {
                                window.location.reload();
                            } else {
                                $.common.showErrorMessage(result.message)
                                return false;
                            }
                        }
                    };
                    $.xAjax(url, 'POST', JSON.stringify(data.field), callback);
                });
            }
        });

        // 执行中订单表格工具事件
        table.on('tool(execTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'show') {
                var index = layer.open({
                    title: '查看采购订单',
                    type: 2,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['95%', '95%'],
                    content: '/static/page1/order1/page2/add.html?purchaseOrderId=' + data.purchaseOrderId
                        + "&supId=" + data.supId+"&isShow=true",
                    data: data,
                    success: function (index, layero) {
                        var body = layer.getChildFrame('body', layero);
                        for (let key in data) {
                            if ('signDate' == key) {
                                let a = util.toDateString(data[key], 'yyyy-MM-dd')
                                body.find("#" + key).val(a);
                                continue;
                            }
                            if ('validStartDate' == key) {
                                let a = util.toDateString(data[key], 'yyyy-MM-dd')
                                body.find("#" + key).val(a);
                                continue;
                            }
                            if ('validEndDate' == key) {
                                let a = util.toDateString(data[key], 'yyyy-MM-dd')
                                body.find("#" + key).val(a);
                                continue;
                            }
                            body.find("#" + key).val(data[key]);
                        }
                    },
                    end: function () {

                    }
                });
                lay(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            } else if (obj.event === 'generateContract') {
                // 生成合同
                layer.confirm('确定为此订单生成合同？', function (index) {
                    $.xAjax('/purchaseContract/generate/' + data.orderNo, 'POST', JSON.stringify({}), {
                        onSuccess: function (result) {
                            if (result.code == 0) {
                                $.common.showSuccessMessage('合同生成成功，合同号：' + (result.data ? result.data.contractNo : ''));
                                table.reload('execTableId');
                            } else {
                                $.common.showErrorMessage(result.message);
                            }
                        },
                        onError: function (xhr, status, error) {
                            $.common.showErrorMessage('生成合同失败：' + error);
                        }
                    });
                    layer.close(index);
                });
            } else if (obj.event === 'rejectForRevision') {
                // 打回重审
                layer.prompt({
                    title: '打回重审原因',
                    formType: 2,
                    area: ['400px', '200px']
                }, function(value, index, elem) {
                    if (!value || value.trim() == '') {
                        $.common.showErrorMessage('请填写打回重审原因');
                        return;
                    }
                    
                    $.xAjax('/purchaseOrder/rejectForRevision/' + data.purchaseOrderId, 'POST', JSON.stringify({rejectReason: value}), {
                        onSuccess: function (result) {
                            if (result.code == 0) {
                                $.common.showSuccessMessage('订单已打回重审');
                                table.reload('execTableId');
                            } else {
                                $.common.showErrorMessage(result.message);
                            }
                        }
                    });
                    layer.close(index);
                });
            }
        });

    });

    function search(data) {
        table.reload('currentTableId', {
            page: {
                curr: 1
            }
            , where: {
                param: data.field
            }
        }, 'data');
    }

    function execSearch(data) {
        // 添加执行状态过滤
        var searchData = data.field;
        searchData.docStatus = '70'; // 只搜索执行状态的订单
        searchData.redFlag = 'NO';   // 只搜索非历史订单
        
        table.reload('execTableId', {
            page: {
                curr: 1
            }
            , where: {
                param: searchData
            }
        }, 'data');
    }
</script>

</body>
</html>